/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.spring;

import com.je.bpm.engine.ManagementService;
import com.je.bpm.engine.RepositoryService;
import com.je.bpm.engine.impl.EventSubscriptionQueryImpl;
import com.je.bpm.engine.impl.interceptor.Command;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.MessageEventSubscriptionEntity;
import com.je.bpm.api.runtime.process.event.impl.StartMessageSubscriptionConverter;
import com.je.bpm.api.runtime.process.impl.APIProcessDefinitionConverter;
import com.je.bpm.model.process.event.impl.StartMessageDeployedEventImpl;
import com.je.bpm.model.process.event.impl.StartMessageDeployedEvents;
import com.je.bpm.model.process.events.StartMessageDeployedEvent;
import com.je.bpm.model.process.model.ProcessDefinition;
import com.je.bpm.model.process.model.impl.StartMessageDeploymentDefinitionImpl;
import com.je.bpm.runtime.process.event.listener.ProcessRuntimeEventListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationEventPublisher;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class StartMessageDeployedEventProducer extends AbstractActivitiSmartLifeCycle {

    private static Logger logger = LoggerFactory.getLogger(StartMessageDeployedEventProducer.class);

    private RepositoryService repositoryService;
    private ManagementService managementService;
    private APIProcessDefinitionConverter converter;
    private StartMessageSubscriptionConverter subscriptionConverter;
    private List<ProcessRuntimeEventListener<StartMessageDeployedEvent>> listeners;
    private ApplicationEventPublisher eventPublisher;

    public StartMessageDeployedEventProducer(RepositoryService repositoryService,
                                             ManagementService managementService,
                                             StartMessageSubscriptionConverter subscriptionConverter,
                                             APIProcessDefinitionConverter converter,
                                             List<ProcessRuntimeEventListener<StartMessageDeployedEvent>> listeners,
                                             ApplicationEventPublisher eventPublisher) {
        this.repositoryService = repositoryService;
        this.managementService = managementService;
        this.subscriptionConverter = subscriptionConverter;
        this.converter = converter;
        this.listeners = listeners;
        this.eventPublisher = eventPublisher;
    }

    @Override
    public void doStart() {
        List<ProcessDefinition> processDefinitions = converter.from(repositoryService.createProcessDefinitionQuery().list());
        List<StartMessageDeployedEvent> messageDeployedEvents = new ArrayList<>();

        for (ProcessDefinition processDefinition : processDefinitions) {
            managementService.executeCommand(new FindStartMessageEventSubscriptions(processDefinition.getId()))
                    .stream()
                    .map(subscriptionConverter::convertToStartMessageSubscription)
                    .map(messageSubscription -> StartMessageDeploymentDefinitionImpl.builder()
                            .withMessageSubscription(messageSubscription)
                            .withProcessDefinition(processDefinition)
                            .build())
                    .map(startMessageDeploymentDefinition -> StartMessageDeployedEventImpl.builder()
                            .withEntity(startMessageDeploymentDefinition)
                            .build())
                    .forEach(messageDeployedEvents::add);
        }

        managementService.executeCommand(new DispatchStartMessageDeployedEvents(messageDeployedEvents));

        if (!messageDeployedEvents.isEmpty()) {
            eventPublisher.publishEvent(new StartMessageDeployedEvents(messageDeployedEvents));
        }
    }

    @Override
    public void doStop() {
        // nothing
    }

    class DispatchStartMessageDeployedEvents implements Command<Void> {
        private final List<StartMessageDeployedEvent> messageDeployedEvents;
        public DispatchStartMessageDeployedEvents(List<StartMessageDeployedEvent> messageDeployedEvents) {
            this.messageDeployedEvents = messageDeployedEvents;
        }

        @Override
        public Void execute(CommandContext commandContext) {
            for (ProcessRuntimeEventListener<StartMessageDeployedEvent> listener : listeners) {
                messageDeployedEvents.stream().forEach(listener::onEvent);
            }

            return null;
        }
    }

    static class FindStartMessageEventSubscriptions implements Command<List<MessageEventSubscriptionEntity>> {

        private static final String MESSAGE = "message";
        private final String processDefinitionId;

        public FindStartMessageEventSubscriptions(String processDefinitionId) {
            this.processDefinitionId = processDefinitionId;
        }

        @Override
        public List<MessageEventSubscriptionEntity> execute(CommandContext commandContext) {
            return new EventSubscriptionQueryImpl(commandContext).eventType(MESSAGE)
                    .configuration(processDefinitionId)
                    .list()
                    .stream()
                    .map(MessageEventSubscriptionEntity.class::cast)
                    .filter(it -> it.getProcessInstanceId() == null)
                    .collect(Collectors.toList());
        }
    }

}
